package cn.itcast.web.controller;
import cn.itcast.domain.compony.Company;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.domain.system.WxUserInfo;
import cn.itcast.service.company.CompanyService;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import cn.itcast.utils.WeiXinUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.List;

@Controller
public class WeiXinLoginController extends BaseController {
    @Autowired
    UserService userService;
    @Autowired
    CompanyService companyService;
    @Autowired
    ModuleService moduleService;

    @RequestMapping("/LoginCallBack")
    public String login() throws IOException, JSONException {


        System.out.println("执行了回调");

        String code = request.getParameter("code");
        //页面请求获取code
        if (code == null) {
            throw new RuntimeException("用户权限不足");
        }

        //请求获取token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + WeiXinUtil.APPID
                + "&secret=" + WeiXinUtil.APPSECRET
                + "&code=" + code
                + "&grant_type=authorization_code";

        WeiXinUtil weiXinUtil = new WeiXinUtil();
        //json类型
        String access_tokenAndOpenid = weiXinUtil.httpGet(url);
        //解析，获取字段
        JSONObject tokenJson = new JSONObject(access_tokenAndOpenid);
        String token = (String) tokenJson.get("access_token");
        String openid = (String) tokenJson.get("openid");

        //请求获取信息
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token=" + token
                + "&openid=" + openid
                + "&lang=zh_CN";

        //json类型
        String userInfoJson = weiXinUtil.httpGet(infoUrl);
        JSONObject userJson = new JSONObject(userInfoJson);

        String headimgurl = (String) userJson.get("headimgurl");
        String nickname = (String) userJson.get("nickname");
        Integer sex = (Integer) userJson.get("sex");
        String language = (String) userJson.get("language");
        String city = (String) userJson.get("city");
        String province = (String) userJson.get("province");
        String country = (String) userJson.get("country");

        System.out.println("昵称:" + nickname);
        System.out.println("性别:" + sex + " (1代表男，2代表女)");
        System.out.println("1代表男，2代表女");
        System.out.println("头像地址 " + headimgurl);
        System.out.println("城市:" + city);
        System.out.println("省市:" + province);
        System.out.println("国家:" + country);

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        WxUserInfo wxUserInfo = mapper.readValue(userInfoJson, WxUserInfo.class);
        System.out.println(wxUserInfo + "   userinfo");

        User user = userService.findByNickname(nickname);

        if (user == null) {
            request.setAttribute("error","微信号尚未注册，请联系贵公司管理员");
            return "forward:/login.jsp";
        } else {
            return wxLogin(user.getEmail(), "123");
        }
        //""
    }
    public String wxLogin(String email, String password){
        //注册了保存用户
        try {
            //2.若可用,获取shiro中的subject
            Subject subject = SecurityUtils.getSubject();

            //3.将用户名和密码进行封装,封装token(令牌)
            UsernamePasswordToken token = new UsernamePasswordToken(email, password);

            //4.调用subject.login(token)方法实现登陆操作
            subject.login(token);

            //5.若执行什么的方法没有异常就证明查询到了用户且密码也对;若有异常就证明有问题
            //6.若成功了,获取主要的数据loginUser
            User loginUser  = (User) subject.getPrincipal();

            // 判断公司是否被禁用
            Company company = companyService.findById(loginUser.getCompanyId());
            if (loginUser.getDegree() != 0 && company.getState() != 1) {
                // 公司若被禁用
                request.setAttribute("error","请联系贵公司的管理员");
                return "forward:/login.jsp";
            }

            session.setAttribute("loginUser",loginUser);

            // 根据用户查询模块列表
            List<Module> modules = moduleService.findModulesByUser(loginUser);
            //将模块列表放入session中
            session.setAttribute("modules",modules);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error","用户名或密码错误");
            return "forward:/login.jsp";
        }
        return "home/main";
    }
}
